package com.jinglin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jinglin.entity.po.VideoInfo;
import com.jinglin.entity.po.VideoPlayHistory;
import com.jinglin.entity.query.SimplePage;
import com.jinglin.entity.vo.PaginationResultVO;
import com.jinglin.mapper.VideoPlayHistoryMapper;
import com.jinglin.service.VideoPlayHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 视频播放历史 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2025-04-03
 */
@Service
public class VideoPlayHistoryServiceImpl extends ServiceImpl<VideoPlayHistoryMapper, VideoPlayHistory> implements VideoPlayHistoryService {
    @Autowired
    private VideoPlayHistoryMapper videoPlayHistoryMapper;
    @Override
    public void saveVideoHistory(VideoPlayHistory videoPlayHistory) {
        LambdaUpdateWrapper<VideoPlayHistory> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(VideoPlayHistory::getUserId,videoPlayHistory.getUserId());
        wrapper.eq(VideoPlayHistory::getVideoId,videoPlayHistory.getVideoId());
        VideoPlayHistory one = this.getOne(wrapper);
        if (one !=null){
            // 不为null，就是以前播放过。我们现在更新播放的index和last_update_time
            wrapper.set(VideoPlayHistory::getFileIndex,videoPlayHistory.getFileIndex());
            wrapper.set(VideoPlayHistory::getLastUpdateTime, LocalDateTime.now());
            this.update(wrapper);
            return;
        }
        this.save(videoPlayHistory);
    }

    @Override
    public PaginationResultVO loadHistory(String userId, Integer pageNo) {
        int count = videoPlayHistoryMapper.count(userId);
        Integer pageSize = 15;

        SimplePage page = new SimplePage(pageNo, count, pageSize);
        List<VideoPlayHistory> list = videoPlayHistoryMapper.loadHistoryList(page.getStart(), pageSize, userId);
        PaginationResultVO<VideoPlayHistory> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);

        return result;
    }
}
